﻿using System;
using System.Collections.ObjectModel;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace NHINDirect
{
    /// <summary>
    /// Extends Collection, but makes sure you cannot put Null elements in
    /// </summary>
    public class ObjectCollection<T> : Collection<T>
    {
        public ObjectCollection()
        {
        }
        
        public ObjectCollection(IEnumerable<T> items)
        {
            this.Add(items);
        }
        
        public void Add(IEnumerable<T> items)
        {
            if (items == null)
            {
                throw new ArgumentNullException();
            }
            
            foreach(T item in items)
            {
                this.Add(item);
            }
        }
        
        /// <summary>
        /// Remove all items matching the given filter
        /// </summary>
        /// <param name="filter"></param>
        public void Remove(Predicate<T> filter)
        {
            this.Remove(filter, true);
        }
        
        /// <summary>
        /// Remove all items EXCEPT those that match this filter
        /// </summary>
        /// <param name="filter"></param>
        public void RemoveExcept(Predicate<T> filter)
        {
            this.Remove(filter, false);
        }

        void Remove(Predicate<T> filter, bool filterResult)
        {
            if (filter == null)
            {
                throw new ArgumentNullException();
            }

            int i = 0;
            int count = this.Count;
            while (i < count)
            {
                if (filter(this[i]) == filterResult)
                {
                    this.RemoveAt(i);
                    count--;
                }
                else
                {
                    ++i;
                }
            }
        }
                   
        protected override void InsertItem(int index, T item)
        {
            if (item == null)
            {
                throw new ArgumentNullException();
            }
            base.InsertItem(index, item);
        }

        protected override void SetItem(int index, T item)
        {
            if (item == null)
            {
                throw new ArgumentNullException();
            }
            base.SetItem(index, item);
        }        
    }
}
